/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  customerOrder
 *  CustomerOrder
 *  customer_order
 */



/***** variables declartion section, begin *****/
var customerOrderInputMode = wacFormInputMode.add;
var customerOrderObj = {};
var customerOrderAuditAction = {};  // process audit action

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        customerOrderAuditAction = new CustomerOrderAuditAction();

        initCustomerOrderFormDialog();

        initCustomerOrderForm();

        bindCustomerOrderEvents();
    }
);

function bindCustomerOrderEvents()
{
    $("#customerOrderFormDialog").bind('dialogopen', function(event, ui)
    {
        initCustomerOrderFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.customerOrder.name);//
    });

    $("#customerOrderFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#customerOrder_btnSubmit").bind('click', function (e)
    {
        submitCustomerOrderForm();
    });

    $("#customerOrder_btnClose").bind('click', function (e)
    {
        $("#customerOrderFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t1002")
        {
            $("div[aria-labelledby='ui-dialog-title-customerOrderFormDialog']").remove();
            $("#customerOrderFormDialog").remove();
        }
    });
}


function initCustomerOrderFormDialog()
{
//    wacDebugLog("initCustomerOrderFormDialog.");
    $("#customerOrderFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 480,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCustomerOrderForm()
{
    $("#customerOrderForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#customerOrder_start_date, #customerOrder_delivery_date").datepicker();
//    $("#start_date, #delivery_date").datepicker({
//        duration: '',
//        showTime: true,
//        constrainInput: false,
//        stepMinutes: 1,
//        stepHours: 1,
//        altTimeField: '',
//        time24h: false
//     });

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });
    
    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });

    
}

function initCustomerOrderFormData()
{
    wacShowBlockUILoading("#customerOrderFormDialog");
    $('#customerOrder_customer_id, #customerOrder_currency_code ').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "customerOrder/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCustomerOrderFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCustomerOrderFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['customer'].length;i++)
        {
            $('<option value="' + jsonData['items']['customer'][i].key +'">' + jsonData['items']['customer'][i].value +'</option>').appendTo("#customerOrder_customer_id");
        }

        for(i=0;i<jsonData['items']['currency'].length;i++)
        {
            $('<option value="' + jsonData['items']['currency'][i].key +'">' + jsonData['items']['currency'][i].value +'</option>').appendTo("#customerOrder_currency_code");
        }
   }

   setupCustomerOrderFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#customerOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCustomerOrderFormDefaultValues(defaultValueObj)
{
    if(customerOrderInputMode == wacFormInputMode.add)   // use default values
    {
        $("#customerOrder_currency_code option:[value='"+ defaultValueObj.currency +"']").attr('selected', 'selected');
        $("#customerOrder_id").attr("value", 0);
    }
    else  // use edit obj values
    {
        $("#customerOrder_start_date").attr("value", customerOrderObj.start_date);
        $("#customerOrder_delivery_date").attr("value", customerOrderObj.delivery_date);
        $("#customerOrder_code").attr("value", customerOrderObj.code);
        $("#customerOrder_id").attr("value", customerOrderObj.id);
        $("#customerOrder_memo").attr("value", customerOrderObj.memo);

        $("#customerOrder_customer_id option:[value='"+ customerOrderObj.customer_id +"']").attr('selected', 'selected');
        $("#customerOrder_currency_code option:[value='"+ customerOrderObj.currency_code +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(customerOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("customerOrderInputMode: " + customerOrderInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

// audit class
function CustomerOrderAuditAction(){
    this.run = function(orderId){
        customerOrderAudit(orderId);
    }
}

function customerOrderAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "customer_order_id" : orderId
    };
//    customerOrderObj = $("#customerOrderList").getRowData(orderId);
//    console.log($.dump(customerOrderObj));

    $.ajax({
        url: BASE_URL + "customerOrder/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            customerOrderAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function customerOrderAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#customerOrderList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function customerOrderOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    customerOrderInputMode = inputMode;

    if(rowid === undefined){
        customerOrderObj = {};
    }
    else
    {
        customerOrderObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCustomerOrderForm()
{
    var validateFlag = true;
    
    if (!$("#customerOrderForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    var startDate    = $("#customerOrder_start_date").datepicker( 'getDate' );
    var deliveryDate = $("#customerOrder_delivery_date").datepicker( 'getDate' );
    if(deliveryDate <= startDate)
    {
        wacShowTips("发货日期不得早于开始日期!");
        validateFlag = false;
    }
    
    return validateFlag;
}

function submitCustomerOrderForm()
{
    if(!validateCustomerOrderForm()){
        return;
    }

    wacShowBlockUILoading("#customerOrderFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(customerOrderInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "customerOrder/add";
    }
    else{
        submitUrl = BASE_URL + "customerOrder/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#customerOrderForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCustomerOrderFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCustomerOrderFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#customerOrderList").trigger("reloadGrid");
   }

   wacHideBlockUI("#customerOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/